// pages/test/test.js
let videoAd = null
// 在页面中定义插屏广告
let interstitialAd = null
let interval =null
Page({

  /**
   * 页面的初始数据
   */
  data: {
    ad:[],
    timeDown:0,
    test:0
  },
  onShow(){
    this.setData({
        ad: []
    });
    this.setData({
      ad:getApp().globalData.adTest
    })
    getApp().chaping()
},

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let that = this
    if (this.data.ad.length>0&&wx.createRewardedVideoAd) {
      videoAd = wx.createRewardedVideoAd({
        adUnitId: that.data.ad.filter(item=>{
          return item.type == 'jili'
        })[0].id
      })
      videoAd.onLoad(() => {})
      videoAd.onError((err) => {})
      videoAd.onClose((res) => {})
    }
    if (this.data.ad.length>0&&wx.createInterstitialAd) {
      interstitialAd = wx.createInterstitialAd({
        adUnitId: that.data.ad.filter(item=>{
          return item.type == 'chaping'
        })[0].id
      })
      interstitialAd.onLoad(() => {})
      interstitialAd.onError((err) => {})
      interstitialAd.onClose(() => {})
    }
  },
  openChaping(){
    let that = this
    if(this.data.timeDown != 0){
      return
    }
    if (interstitialAd) {
      interstitialAd.show()
      .then(()=>{
        console.log(111)
        that.resetTime()
      })
      .catch((err) => {
        console.error(err)
      })
    }
  },
  resetTime(){
    let that = this
    clearInterval(interval)
    that.setData({
      timeDown:20
    })
    interval = setInterval(function(){
      if(that.data.timeDown>0){
        that.setData({
          timeDown:that.data.timeDown-1
        })
      }
    },1000)
  },
  openJili(){
    let that = this
    if (videoAd) {
      videoAd.show()
      .then(()=>{
        that.resetTime()
      })
      .catch(() => {
        // 失败重试
        videoAd.load()
          .then(() => videoAd.show().then(()=>{
            that.resetTime()
          }))
          .catch(err => {
            console.log('激励视频 广告显示失败')
          })
      })
    }
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})